package com.home.security.app.token;

import com.home.security.app.constants.RedisKeyConstants;

import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 密钥/公钥
 * Created by 王大宸 on 2020-12-11 11:08
 * Created with IntelliJ IDEA.
 */
public class RsaKeyHelper {

    /***
     * 功能说明： 获取公钥
     *
     * @author 王大宸
     * @date 2020/7/8 9:40
     * @param publicKey publicKey
     * @return java.security.PublicKey
     */
    public static PublicKey getPublicKey(byte[] publicKey) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf = KeyFactory.getInstance(RedisKeyConstants.KEY_PAIR_INSTANCE);
        return kf.generatePublic(spec);
    }

    /***
     * 功能说明：获取密钥
     *
     * @author 王大宸
     * @date 2020/7/8 9:41
     * @param privateKey privateKey
     * @return java.security.PrivateKey
     */
    public static PrivateKey getPrivateKey(byte[] privateKey) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory kf = KeyFactory.getInstance(RedisKeyConstants.KEY_PAIR_INSTANCE);
        return kf.generatePrivate(spec);
    }

    /***
     * 功能说明：生成 key
     *
     * @author 王大宸
     * @date 2020/7/8 10:10
     * @param password password
     * @return java.util.Map<java.lang.String,byte[]>
     */
    public static Map<String, byte[]> generateKey(String password) throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RedisKeyConstants.KEY_PAIR_INSTANCE);
        SecureRandom secureRandom = new SecureRandom(password.getBytes());
        keyPairGenerator.initialize(1024, secureRandom);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
        byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
        Map<String, byte[]> map = new HashMap<String, byte[]>();
        map.put("pub", publicKeyBytes);
        map.put("pri", privateKeyBytes);
        return map;
    }


    public static String toHexString(byte[] b) {
        return Base64.getEncoder().encodeToString(b);
    }

    public static final byte[] toBytes(String s) throws IOException {
        return Base64.getMimeDecoder().decode(s);
    }

}
